import httplib, urllib
import md5
import simplejson as json
import gtk, gobject
import time
from collections import deque
from NetlogMusicConf import NetlogMusicConf


class NetlogCommunicator:

	API_KEY="c2b5e31e3c938c186f093420a8fd44a1"
				 
				  
	def __init__(self, config):
		self.config = config
		self.postpath = "/comcore-api/apiserver/action=callMethod&format=json2"
		self.reqId = 0
		self.loggedIn = False
		self.update_settings(self.config.get_bool("autologin"))
	
	def update_settings(self, with_login):
		self.nickname = self.config.get("username")
		self.domain = self.config.get("domain")+":80"
		self.password = self.config.get("password")
		if with_login:
			if self.loggedIn:
				self.logout()
			self.request_ticket()
			self.login()
		
	def isLoggedIn(self):
		return self.loggedIn
		
	def make_sig(self, params):
		sig = ""
		order = params.keys()
		order.remove('sig')
		order.sort()
	
		for k in order:
			sig += params[k]
		sig += NetlogCommunicator.API_KEY
		return md5.new(sig).hexdigest()
				
	def post(self, params):
		header = {'Content-Type':'application/x-www-form-urlencoded'}
		self.reqId += 1
	
		if "requestId" in params:
			params["requestId"] = str(self.reqId)
		if "ticket" in params:
			params["ticket"] = self.ticket
		if "sig" in params:
			params["sig"] = self.make_sig(params)	
		params = urllib.urlencode(params)
		
		conn = httplib.HTTPConnection(self.domain)
		conn.request("POST", self.postpath, params, header)
		resp = conn.getresponse()
		
		obj = json.loads(resp.read())
		if "response" in obj:
			return obj["response"]
		if "error" in obj:
			return obj["error"]
		
	def request_ticket(self):
		getTicketParams = {'app_version': '3.0-Ryhthm', 
				 	 	   'appid': 'com.netlog.musictool',
				 	 	   'method': 'auth.getTicket',
				 	 	   'version': '1.0'}
		response = self.post(getTicketParams)
		self.ticket = response["ticket"]
		print response
		
	def login(self):
		loginData = {'key': md5.new(self.ticket+self.password).hexdigest(),
				 'method':'auth.login',
				 'nickname':self.nickname,
				 'requestId':'',
				 'sig':'',
				 'ticket':''}
		response = self.post(loginData)
		print response 
		if "login" in response and bool(response["login"]):
			self.loggedIn = True
	
	def logout(self):
		logoutData = {'method':'auth.logout',
				  'requestId':'',
				  'sig':'',
				  'ticket':''}
		response = self.post(logoutData)
		print response
		self.ticket = None
		self.loggedIn = False
	
	def sendSong(self, songInfo):
		songInfo["send_time"] = time.ctime()
		self.post(songInfo)
		
